package com.sparrow.common.ai.behaviortree.task.impl;

import com.sparrow.common.ai.behaviortree.def.BTNodeStatus;
import com.sparrow.common.ai.behaviortree.BehaviorContext;
import com.sparrow.common.ai.behaviortree.node.BehaviorNode;
import com.sparrow.common.ai.behaviortree.node.impl.SelectorNode;
import com.sparrow.common.ai.behaviortree.task.BehaviorTask;
import java.util.ArrayList;
import java.util.List;
/**
 * 逐个执行子节点，直到一个子节点成功。也叫“优先选择”节点。
 * ps: 优先选择其中一个
 */
public class SelectorTask extends BehaviorTask {
    private final List<BehaviorTask> childTasks = new ArrayList<>();
    private final SelectorNode node;
    private int currentIndex = 0;

    public SelectorTask(SelectorNode node) {
        this.node = node;
        for (BehaviorNode child : node.getChildren()) {
            this.childTasks.add(child.createTask());
        }
    }

    @Override
    public BTNodeStatus tick(BehaviorContext context, long now, long delta) {
        while (currentIndex < childTasks.size()) {
            BehaviorTask task = childTasks.get(currentIndex);
            BTNodeStatus status = task.tick(context, now, delta);
            if (status == BTNodeStatus.SUCCESS) {
                currentIndex = 0; // reset for next tick
                return BTNodeStatus.SUCCESS;
            }
            if (status == BTNodeStatus.RUNNING) {
                return BTNodeStatus.RUNNING;
            }
            currentIndex++;
        }
        currentIndex = 0; // all failed, reset
        return BTNodeStatus.FAILURE;
    }

    @Override
    public String toString() {
        return "SelectorTask{" +
                "childTasks=" + childTasks +
                ", node=" + node +
                ", currentIndex=" + currentIndex +
                '}';
    }
}
